<template>
  <div class="accounts-payable-summary">
    <!-- 查询条件区域 -->
    <div class="search-container">
      <div class="search-row">
        <div class="date-range">
          <span class="label">单据日期:</span>
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
          <span class="to-text">至</span>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
        </div>

        <div class="search-item">
          <span class="label">供应商</span>
          <el-input
            v-model="selectedSupplierNames"
            placeholder="请选择供应商"
            readonly
            class="supplier-input"
            @click="openSupplierDialog"
          >
            <template #suffix>
              <el-icon class="select-icon" @click="openSupplierDialog">
                <ArrowDown />
              </el-icon>
            </template>
          </el-input>
        </div>

        <div class="search-item">
          <span class="label">供应商类别</span>
          <el-select
            v-model="category"
            placeholder="供应商类别"
            class="search-select"
          >
            <el-option label="全部类别" value="" />
            <el-option
              v-for="item in supplierCategories"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>

        <div class="search-actions">
          <el-button type="primary" @click="doSearch" class="query-btn"
            >查询</el-button
          >
          <el-button @click="expandConditions" class="expand-btn"
            >展开条件</el-button
          >
        </div>
      </div>

      <!-- 高级查询条件 (默认隐藏) -->
      <div class="advanced-search" v-if="showAdvancedSearch">
        <!-- 可添加更多高级查询条件 -->
      </div>
    </div>

    <!-- 饼状图区域 -->
    <div class="chart-container" v-if="showChart">
      <h2 style="text-align: center">应付账款总览</h2>
      <div class="chart-item" ref="pieChartRef">
        <div class="chart-title">供应商应付款占比</div>
        <div class="chart-content"></div>
      </div>
    </div>

    <!-- 报表标题区域 -->
    <div class="report-header">
      <div class="date-range-text">日期: {{ startDate }} 至 {{ endDate }}</div>
      <h2 class="report-title">应付账款汇总表</h2>
      <div class="report-actions">
        <el-button type="primary" class="export-btn">导出</el-button>
        <el-dropdown class="print-btn">
          <el-button type="primary">
            打印
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>打印预览</el-dropdown-item>
              <el-dropdown-item>直接打印</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 表格工具栏 -->
    <!-- <div class="table-tools">
      <el-button type="text" @click="openSupplierDialog" class="select-supplier-btn">
        <el-icon><user /></el-icon> 选择供应商
      </el-button>
      <span class="selected-count" v-if="selectedSuppliers.length > 0">
        已选择 {{ selectedSuppliers.length }} 个供应商
      </span>
    </div> -->

    <!-- 数据表格 -->
    <el-table
      :data="filteredTableData"
      border
      :row-class-name="tableRowClassName"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      class="summary-table"
      highlight-current-row
    >
      <el-table-column
        prop="supplierCategory"
        label="供应商类别"
        min-width="100"
        sortable
      />
      <el-table-column
        prop="supplierCode"
        label="供应商编号"
        min-width="100"
        sortable
      />
      <el-table-column
        prop="supplierName"
        label="供应商名称"
        min-width="150"
        sortable
      />
      <el-table-column
        prop="beginningBalance"
        label="期初余额"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>期初余额</span>
            <el-tooltip effect="dark" content="期初余额说明">
              <el-icon class="question-icon"><question-filled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="currentPayable"
        label="本期应付"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>本期应付</span>
            <el-tooltip effect="dark" content="本期应付说明">
              <el-icon class="question-icon"><question-filled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="currentPayment"
        label="本期付款"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>本期付款</span>
            <el-tooltip effect="dark" content="本期付款说明">
              <el-icon class="question-icon"><question-filled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="endingBalance"
        label="期末余额"
        min-width="120"
        align="right"
      >
        <template #header>
          <div class="header-with-tooltip">
            <span>期末余额</span>
            <el-tooltip effect="dark" content="期末余额说明">
              <el-icon class="question-icon"><question-filled /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 供应商选择对话框组件 -->
    <supplier-multiple-select-dialog
      ref="supplierSelectDialogRef"
      :supplier-list="allSuppliers"
      @confirm="handleSupplierConfirm"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from "vue";
import { ArrowDown, QuestionFilled } from "@element-plus/icons-vue";
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
} from "echarts/components";
import { PieChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import SupplierMultipleSelectDialog from "@/util/SupplierMultipleSelectDialog.vue";
import dayjs from "dayjs";

// 注册ECharts组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
]);

// 图表相关
const pieChartRef = ref(null);
const pieInstance = ref(null);
const showChart = ref(true);
const supplierSelectDialogRef = ref(null);

// 日期范围
const startDate = ref(dayjs().startOf('month').format('YYYY-MM-DD'));
const endDate = ref(dayjs().format('YYYY-MM-DD')) 

// 查询条件
const category = ref("");
const showAdvancedSearch = ref(false);
const selectedSuppliers = ref([]);

// 合并的供应商数据（包含基本信息和财务数据）
const mockSuppliersData = ref([
  {
    SupplierCode: "S00001",
    SupplierName: "东莞材料供应商",
    SupplierType: "原材料供应商",
    SupplierConcat: "张经理",
    SupplierPhone: "13500135000",
    financialData: {
      beginningBalance: "-1,992.02",
      currentPayable: "500.00",
      currentPayment: "200.00",
      endingBalance: "-1,692.02"
    }
  },
  {
    SupplierCode: "S00002",
    SupplierName: "广州服务供应商",
    SupplierType: "服务供应商",
    SupplierConcat: "李经理",
    SupplierPhone: "13600136000",
    financialData: {
      beginningBalance: "-2,064.99",
      currentPayable: "1,000.00",
      currentPayment: "500.00",
      endingBalance: "-1,564.99"
    }
  },
  {
    SupplierCode: "S00003",
    SupplierName: "深圳设备供应商",
    SupplierType: "设备供应商",
    SupplierConcat: "王经理",
    SupplierPhone: "13700137000",
    financialData: {
      beginningBalance: "-3,000.00",
      currentPayable: "2,000.00",
      currentPayment: "1,500.00",
      endingBalance: "-2,500.00"
    }
  }
]);

// 计算属性：获取所有供应商列表（不含财务数据）
const allSuppliers = computed(() => {
  return mockSuppliersData.value.map(supplier => {
    return {
      SupplierCode: supplier.SupplierCode,
      SupplierName: supplier.SupplierName,
      SupplierType: supplier.SupplierType,
      SupplierConcat: supplier.SupplierConcat,
      SupplierPhone: supplier.SupplierPhone
    };
  });
});

// 计算属性：供应商类别
const supplierCategories = computed(() => {
  const categories = new Set();
  mockSuppliersData.value.forEach((supplier) => {
    if (supplier.SupplierType) categories.add(supplier.SupplierType);
  });
  return Array.from(categories);
});

// 计算属性：已选择供应商名称字符串
const selectedSupplierNames = computed(() => {
  return selectedSuppliers.value.map((s) => s.SupplierName).join(", ");
});

// 计算属性：过滤后的表格数据（只显示选中的供应商）
const filteredTableData = computed(() => {
  if (selectedSuppliers.value.length === 0) {
    return tableData.value;
  }
  
  return tableData.value.filter(row => 
    selectedSuppliers.value.some(s => s.SupplierCode === row.supplierCode) ||
    row.supplierCategory === "合计"
  );
});

// 表格数据
const tableData = ref([]);

// 表头样式
const headerCellStyle = {
  backgroundColor: "#f5f7fa",
  fontWeight: "bold",
  color: "#303133",
  textAlign: "center",
};

// 计算合计行数据
const calculateSummaryRow = (data) => {
  const summary = {
    supplierCategory: "合计",
    supplierCode: "",
    supplierName: "",
    beginningBalance: "0",
    currentPayable: "0",
    currentPayment: "0",
    endingBalance: "0",
  };

  data
    .filter((item) => item.supplierCategory !== "合计")
    .forEach((item) => {
      summary.beginningBalance = addCurrency(
        summary.beginningBalance,
        item.beginningBalance
      );
      summary.currentPayable = addCurrency(
        summary.currentPayable,
        item.currentPayable
      );
      summary.currentPayment = addCurrency(
        summary.currentPayment,
        item.currentPayment
      );
      summary.endingBalance = addCurrency(
        summary.endingBalance,
        item.endingBalance
      );
    });

  return summary;
};

// 辅助函数：货币金额相加
const addCurrency = (a, b) => {
  const numA = parseFloat(a.toString().replace(/,/g, "")) || 0;
  const numB = parseFloat(b.toString().replace(/,/g, "")) || 0;
  return (numA + numB).toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

// 更新表格数据（自动计算合计行）
const updateTableData = (newData) => {
  const dataWithoutSummary = newData.filter(
    (item) => item.supplierCategory !== "合计"
  );
  const summaryRow = calculateSummaryRow(dataWithoutSummary);
  tableData.value = [...dataWithoutSummary, summaryRow];
  updatePieChart();
};

// 单元格样式
const cellStyle = ({ row }) => {
  if (row.supplierCategory === "合计") {
    return {
      backgroundColor: "#fff8e6",
      fontWeight: "bold",
    };
  }
  return { textAlign: "center" };
};

// 行类名
const tableRowClassName = ({ row }) => {
  return row.supplierCategory === "合计" ? "summary-row" : "";
};

// 查询数据
const doSearch = () => {
  console.log("查询条件:", {
    startDate: startDate.value,
    endDate: endDate.value,
    selectedSuppliers: selectedSuppliers.value,
    category: category.value,
  });

  // 从合并的数据源生成表格数据
  const tableDataFromSource = mockSuppliersData.value.map(supplier => {
    return {
      supplierCategory: supplier.SupplierType,
      supplierCode: supplier.SupplierCode,
      supplierName: supplier.SupplierName,
      ...supplier.financialData
    };
  });

  // 如果有选中的供应商，则过滤数据
  const filteredData = selectedSuppliers.value.length > 0
    ? tableDataFromSource.filter(row => 
        selectedSuppliers.value.some(s => s.SupplierCode === row.supplierCode)
      )
    : tableDataFromSource;

  updateTableData(filteredData);
};

// 展开/收起高级条件
const expandConditions = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value;
};

// 打开供应商对话框
const openSupplierDialog = () => {
  supplierSelectDialogRef.value?.open();
};

// 处理供应商选择确认
const handleSupplierConfirm = (selected) => {
  selectedSuppliers.value = selected;
  doSearch(); // 重新查询数据
};

// ================== 饼图相关 ==================
// 初始化饼图
const initPieChart = () => {
  nextTick(() => {
    if (pieChartRef.value && !pieInstance.value) {
      const chartDom = pieChartRef.value.querySelector(".chart-content");
      pieInstance.value = echarts.init(chartDom);
      updatePieChart();

      // 响应式调整大小
      window.addEventListener("resize", () => {
        pieInstance.value?.resize();
      });
    }
  });
};

// 获取饼图数据（根据选中的供应商）
const getPieDataFromTable = () => {
  // 如果没有选择供应商，则显示所有数据
  const dataToShow = selectedSuppliers.value.length > 0 
    ? tableData.value.filter(row => 
        selectedSuppliers.value.some(s => s.SupplierCode === row.supplierCode)
      )
    : tableData.value;

  return dataToShow
    .filter((item) => item.supplierCategory !== "合计")
    .map((item) => ({
      value: Math.abs(parseFloat(item.endingBalance.replace(/,/g, "")) || 0),
      name: item.supplierName || "未命名供应商",
      supplierCode: item.supplierCode
    }));
};

// 更新饼图
const updatePieChart = () => {
  if (!pieInstance.value) return;

  const pieData = getPieDataFromTable();
  
  // 如果没有数据，显示空状态
  if (pieData.length === 0) {
    pieInstance.value.setOption({
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          fontSize: 16,
          fontWeight: "normal",
          color: "#999"
        }
      },
      series: []
    });
    return;
  }

  const option = {
    title: {
      text: "供应商应付款占比",
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params) => {
        const selectedSupplier = selectedSuppliers.value.find(
          s => s.SupplierCode === params.data.supplierCode
        );
        const contactInfo = selectedSupplier 
          ? `<br/>联系人: ${selectedSupplier.SupplierConcat || '无'}
             <br/>电话: ${selectedSupplier.SupplierPhone || '无'}`
          : '';
        
        return `
          <strong>${params.name}</strong><br/>
          金额: ${params.value.toLocaleString("zh-CN", {
            style: "currency",
            currency: "CNY",
          })}<br/>
          占比: ${params.percent}%
          ${contactInfo}
        `;
      },
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: "应付款占比",
        type: "pie",
        radius: ["40%", "70%"],
        data: pieData,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          formatter: "{b}: {c}元",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: true,
        },
      },
    ],
  };

  pieInstance.value.setOption(option);
};

// 监听选中的供应商变化，更新饼图
watch(selectedSuppliers, () => {
  updatePieChart();
}, { deep: true });

// 初始化
onMounted(() => {
  // 初始化默认选中的供应商
  selectedSuppliers.value = [...allSuppliers.value];

  // 初始化表格数据
  doSearch();

  // 初始化图表
  initPieChart();
});
</script>

<style scoped>
.accounts-payable-summary {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.date-range {
  display: flex;
  align-items: center;
}

.date-range .label {
  margin-right: 10px;
  font-weight: bold;
}

.to-text {
  margin: 0 10px;
}

.date-picker {
  width: 150px;
}

.search-item {
  display: flex;
  align-items: center;
}

.search-item .label {
  margin-right: 10px;
  font-weight: bold;
  white-space: nowrap;
}

.supplier-input {
  width: 200px;
}

.select-icon {
  cursor: pointer;
}

.search-select {
  width: 150px;
}

.search-actions {
  margin-left: auto;
}

.query-btn,
.expand-btn {
  margin-left: 10px;
}

.advanced-search {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.chart-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-item {
  margin-top: 20px;
}

.chart-title {
  text-align: center;
  font-weight: bold;
  margin-bottom: 10px;
}

.chart-content {
  height: 400px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.date-range-text {
  color: #666;
}

.report-title {
  margin: 0;
  text-align: center;
  flex-grow: 1;
}

.report-actions {
  display: flex;
  gap: 10px;
}

.table-tools {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.select-supplier-btn {
  margin-right: 15px;
}

.selected-count {
  color: #666;
  font-size: 14px;
}

.summary-table {
  width: 100%;
  margin-bottom: 20px;
}

.header-with-tooltip {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.question-icon {
  margin-left: 5px;
  color: #909399;
  cursor: pointer;
}

:deep(.summary-row) {
  background-color: #fff8e6;
}

:deep(.el-table .el-table__header th) {
  background-color: #f5f7fa !important;
}

:deep(.el-table .el-table__row.summary-row) {
  background-color: #f8f8f8 !important;
  font-weight: bold;
}

:deep(.el-table .el-table__row.summary-row:hover > td) {
  background-color: #fff4bf !important;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}
</style>